import cv2
from PIL import Image, ImageDraw, ImageFont
import pyzbar.pyzbar as pyzbar
import queue
import time

class OCR_scan_bar():
    def __init__(self, sinOUT=None):
        self.frame = None
        self.cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)    # cv2.CAP_DSHOW 警告
        self.OCRq = queue.Queue()
        self.barList = []
        self.BOX_num = 11
        self.time1 = 0
        self.sinOUT = sinOUT  # 信号

    def start(self):
        self.sinOUT.emit("OCR&OCR开始运行")
        barcodeData1 = ''
        test = None
        eTime = 0
        barcodes = None
        while True:
            ret, self.frame = self.cap.read()
            self.frame = cv2.flip(self.frame, 1)
            time.sleep(0.01)
            while not test:
                # text = pyzbar.decode(self.frame)
                # text = pyzbar.decode(self.frame,ymbols=[64])
                gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
                # barcodes = pyzbar.decode(gray, symbols=[64])
                barcodes = pyzbar.decode(gray)
                if eTime > 5:
                    break
                eTime += 1
            for barcode in barcodes:
                (x, y, w, h) = barcode.rect
                cv2.rectangle(self.frame, (x, y), (x + w, y + h), (255, 255, 0), 2)
                barcodeData = barcode.data.decode("utf-8")
                barcodeType = barcode.type
                if barcodeData == '' or barcodeData != barcodeData1:
                    barcodeData1 = barcodeData   #  防止从新扫描
                    # ======================可以不需要，这是在图片上进行标注，里面采用了字体文件==============================
                    img_PIL = Image.fromarray(cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB))
                    font = ImageFont.truetype('arialbd.ttf', 25)  # 前面是字体文件，后面是字号
                    fillColor = (0, 255, 0)
                    position = (x, y - 25)
                    strl = barcodeData
                    draw = ImageDraw.Draw(img_PIL)
                    draw.text(position, strl, font=font, fill=fillColor)
                    # img_PIL.save('Identification_results.jpg', 'jpeg')  # 保存一张标记过的图片
                    # print("Recognize result>>> type： {0}  content： {1}".format(barcodeType, barcodeData))
                    if self.barList:
                        if barcodeData not in self.barList:
                            self.sinOUT.emit("OCR&" + barcodeData)      # 窗口消息
                            self.barList.append(barcodeData)
                            # print(time.time() - self.time1)
                            # print(self.barList)
                            self.time1 = time.time()
                        else:
                            continue
                    else:
                        print(type(barcodeData))
                        self.sinOUT.emit("OCR&%s" % barcodeData)  # 窗口消息
                        self.barList.append(barcodeData)
                else:
                    pass
            cv2.namedWindow("OCR", 0)
            cv2.imshow('OCR', self.frame)
            k = cv2.waitKey(32)
            if k == 27:
                # 临时数据配置
                import configparser
                OCR_read = configparser.ConfigParser()
                OCR_read.read(r'E:\OCR_RMC\ORC_BAR2.0\OCR_RMC\H_OCR.ini', encoding='utf8')
                OCR_bar = OCR_read.get('OCR_bar', 'bar')
                OCR_bar_list = OCR_bar.split(",")
                # self.OCRq.put(self.barList)
                self.OCRq.put(OCR_bar_list)
                cv2.destroyAllWindows()
                cv2.destroyWindow("OCR")
                self.sinOUT.emit("OCR&胶箱数为: %s" % str(len(OCR_bar_list)))
                self.sinOUT.emit("OCR&OCR结束运行")
                break


